﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MyCommon.Helper;
using MyCommon.Seed;
using SqlSugar.Extensions;

namespace MyExtension.HostedService
{
    public class SeedDataHostedService : IHostedService
    {
        private readonly MyContext _myContext;
        private readonly IWebHostEnvironment _environment;
        private readonly ILogger<SeedDataHostedService> _logger;

        public SeedDataHostedService(MyContext myContext, IWebHostEnvironment environment, ILogger<SeedDataHostedService> logger)
        {
            _myContext = myContext;
            _environment = environment;
            _logger = logger;
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("开始初始化数据库和数据");
            if (Appsettings.app("Appsettings", "SeedDbEnabled").ObjToBool() || Appsettings.app("Appsettings", "SeedDbDataEnabled").ObjToBool())
            {
                try
                {
                    await DBSeed.SeedDataAsync(_myContext, _environment.WebRootPath);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error occured seeding the database");
                    throw;
                }

            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Stop Initialization Db Seed Service!");
            return Task.CompletedTask;
        }
    }
}
